package event

import (
	"strings"
	"sync"
)

type EventHandler func(v interface{})

type EventBus struct {
	Bus map[string][]EventHandler
}

func (eb *EventBus) Subscribe(name string, handler EventHandler) {
	eventNames := strings.Split(name, " ")
	for _, eventName := range eventNames {
		eb.Bus[eventName] = append(eb.Bus[eventName], handler)
	}
}

func (eb *EventBus) Publish(name string, data interface{}) {
	handlers, ok := eb.Bus[name]
	if ok {
		var wg sync.WaitGroup
		wg.Add(len(handlers))
		ch := make(chan int, 10)
		for _, handler := range handlers {
			ch <- 1
			go func(handler2 EventHandler) {
				handler2(data)
				wg.Done()
				<-ch
			}(handler)
		}
		wg.Wait()
	}
}
